package com.heima.example.chat.server.handler;

import com.heima.example.chat.message.ChatRequestMessage;
import com.heima.example.chat.message.ChatResponseMessage;
import com.heima.example.chat.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author ZhengDp
 * @Date 2023/6/30 21:06
 */
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        String to = msg.getTo();
        // 找到对应的 Channel
        Channel toChannel = SessionFactory.getSession().getChannel(to);
        // 在线
        if(toChannel != null) {
            toChannel.writeAndFlush(new ChatResponseMessage(msg.getFrom(),msg.getContent()));
        } else {
            // 向发送者返回消息
            ctx.writeAndFlush(new ChatResponseMessage(false,"对方用户不存在/不在线"));
        }
    }
}
